import OsDimensionApi from '@/api/user/org/osDimension'
import OsRelTypeApi from '@/api/user/org/osRelType'
import OsGroupApi from '@/api/user/org/osGroup'
import OsUserApi from '@/api/user/org/osUser'
import OsRankTypeApi from '@/api/user/org/osRankType'
import OsGroupMenuEdit from "@/views/modules/user/org/OsGroupMenuEdit"
import OsUserEdit from "@/views/modules/user/org/OsUserEdit"
import OsRelInstEdit from "@/views/modules/user/org/OsRelInstEdit"
import {Dialog, Util} from '@lowcode/jpaas-common-lib'
import OsGroupPrivilegeList from "@/views/modules/user/org/OsGroupPrivilegeList"
import { debounce } from 'lodash-es'

export default {
    data() {
        return {
            //维度数组
            dimAry: [],
            //当前维度
            currentDim:{},
            //数据展示类型 TREE=树型数据。FLAT=平铺数据
            dimShowType:"",
            //维度等级数据
            rankData: [],
            //当前选择组织ID
            currentGroupId: '',
            //选中的组对象
            currentGroup: {},
            //当前等级
            rankLevel: -1,
            //搜索标记
            searchFlag:false,
            //搜索结果
            searchResult:[],
            //需要展开树的键
            expandedKeyList:[],
            //用户组
            groupData:[],
            //树形选中的数据
            selectKey:[],

            userActiveKey: '',
            userPanes: [],
            groupActiveKey: '',
            groupPanes: [],

            fullname: '',
            userNo: '',
            tenantId: "",
            //组织类型(1,单位,2,部门)
            orgType: -1,


            //组织分级管理开关
            supportGrade: false,
            //用户组的总数
            totalCount:0
        }
    },
    computed: {

        //当前维度ID
        currentDimId(){
            if(this.currentDim.key){
                return this.currentDim.key;
            }
            return "";
        },
        /**
         * 等级名称
         * @returns {string|*}
         */
        rankName(){
            if(!this.rankData || this.rankData.length==0){
                return "";
            }
            let ary= this.rankData.filter(item=>this.currentGroup.rankId==item.value);
            if(ary.length>0){
                return ary[0].title;
            }
            return "";
        },
        /**
        *  获取查询结果。
        */
        groupDatasource(){
             return this.searchFlag ?this.searchResult:this.groupData;
        }
    },
    created() {
        //获取
        this.getSupportGradeConfig();

        this.init();

    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"osGroup",key);
        },
        init(id, isTab) {
            //获取传入的租户。
            if (!id && this.$route.params.tenantId && !isTab) {
                this.tenantId = this.$route.params.tenantId;
            } else {
                this.tenantId = id;
            }
            let self = this;
            OsDimensionApi.getDimList(this.tenantId).then(res => {
                const data = res.data
                self.dimAry = data.map(item=>{
                    return {
                        key: item.dimId,
                        value: item.dimId, // value是给modal的select用的，2者属性不一样
                        title: item.name,
                        isGrant: item.isGrant,
                        showType: item.showType,
                    }
                });
                //默认选择行政组织。
                self.currentDim=self.dimAry[0];

                this.handDimChange(self.currentDim);
            })
        },

        mainChange(activeKey) {
            const pans = this[activeKey + "Panes"]
            if (pans.length > 0) {
                this.$refs[pans[0].key][0].init()
            }
        },
        userChange(activeKey) {
            this.$refs[activeKey][0].init()
        },
        groupChange(activeKey) {
            this.$refs[activeKey][0].init()
        },
        addUser() {
            if (!this.currentGroupId) {
                this.$message.error(this.i18n('msa.selGroupTips','请选择用户组行！'));
                return;
            }

            var title = this.i18n('userRel.addTitle','新建用户')
            var params = {
                group: this.currentGroup,
                groupId: this.currentGroupId,
                relTypeId: this.$refs[this.userActiveKey][0].relTypeId
            };
            if(this.currentDim && "1"==this.currentDimId && "1"!=params.relTypeId){
                params.newAndJoin=true
            }
            if (this.tenantId) {
                params.tenantId = this.tenantId;
            }
            var conf = {
                curVm: this,
                data: params,
                widthHeight: ['800px', '550px'],
                component: OsUserEdit,
                title: title
            };
            Util.open(conf, function (action) {
                var self = this.$parent;
                self.$refs[self.userActiveKey][0].init();
            });
        },
        joinUser() {
            if (!this.currentGroupId) {
                this.$message.error(this.i18n('msa.selGroupTips','请选择用户组行！'));
                return;
            }
            Dialog.openUserDialog({
                curVm: this, data: {single: false, tenantId: this.tenantId}, widthHeight: ['1100px', '600px']
            }, function (self, users) {
                if (users == null || users.length == 0) {
                    self.$message.error(this.i18n('msa.selUserTips','未选择用户！'));
                    return;
                }
                var userIds = [];
                for (var i = 0; i < users.length; i++) {
                    userIds.push(users[i].userId);
                }
                var tab = self.$refs[self.userActiveKey][0];

                var params = "userIds=" + encodeURIComponent(userIds.join(',')) +
                    "&relTypeId=" + tab.relTypeId +
                    "&groupId=" + self.currentGroupId;

                OsUserApi.joinUser(params).then(res => {
                    if (res.success) {
                        self.$refs[self.userActiveKey][0].init();
                    } else {
                        self.$message.error(res.message);
                    }
                })
            })
        },
        delByUserId() {

            this.$refs[this.userActiveKey][0].removeSelectUser()
        },
        userSearch() {
            const fullname = this.fullname;
            const userNo = this.userNo;
            this.$refs[this.userActiveKey][0].init({fullname: fullname, userno: userNo},true)
        },
        addGroupRelType(record) {
            var self_ = this;
            if (!this.currentGroupId) {
                this.$message.error(self_.i18n('msa.selGroupTips','请选择用户组行！'));
                return;
            }
            var dimId = this.$refs[this.groupActiveKey][0].dimId2;
            var params = {single: false, dimId: dimId, showDimId: true};
            if (self_.tenantId) {
                params.tenantId = self_.tenantId;
            }
            Dialog.openGroupDialog({
                curVm: this, data: params, widthHeight: ['800px', '600px']
            }, function (self, groups) {
                if (groups == null || groups.length == 0) {
                    self.$message.error(this.i18n('groupRel.noSelGroupTips','未选择用户组！'));
                    return;
                }
                var groupIds = [];
                //为多个用户组
                for (var i = 0; i < groups.length; i++) {
                    groupIds.push(groups[i].groupId);
                }
                var params = "groupId=" + self.currentGroupId +
                    "&relTypeId=" + self.$refs[self.groupActiveKey][0].relTypeId +
                    "&groupIds=" + groupIds.join(',');
                if (self_.tenantId) {
                    params += "&tenantId=" + self_.tenantId;
                }

                OsGroupApi.joinGroups(params).then(res => {
                    if (res.success) {
                        self.$refs[self.groupActiveKey][0].init();
                    } else {
                        self.$message.error(res.message);
                    }
                })
            })
        },
        addGroupRelInst() {
            var self_ = this;
            if (!this.currentGroup) {
                this.$message.error(self_.i18n('msa.selGroupTips','请选择用户组行！'));
                return;
            }
            let relType = this.$refs[this.groupActiveKey][0];
            let baseConf = {
                curVm: this,
                widthHeight: ['500px', '550px'],
                component: OsRelInstEdit,
                title: self_.i18n('groupRel.addTitle','新增组关系'),
                data: {
                    relTypeId: relType.relTypeId,
                    relType: relType.relType,
                    relTypeKey: relType.relTypeKey,
                    relTypeDimId2: relType.dimId2,
                    dimId: this.currentGroup.dimId,
                    groupId: this.currentGroup.groupId,
                    groupName: this.currentGroup.name,
                    tenantId: self_.tenantId ? self_.tenantId : ''
                }
            };
            Util.open(baseConf, function (action) {
                if (action != 'ok') return;
                self_.$refs[self_.groupActiveKey][0].init();
            });

        },
        removeGroupRelType() {
            this.$refs[this.groupActiveKey][0].removeSelectGroup()
        },

        assignMenu(record) {
            let params={};
            let widthHeight=['500px', '550px'];
            let title="";
            let component=OsGroupMenuEdit;
           if(this.currentDim.showType=="TREE"){
               params = {
                   groupId: record.groupId,
                   groupName: record.name,
                   dimId: record.dimId,
                   showSearch:false
               };
               widthHeight=['1000px', '600px'];
               component=OsGroupPrivilegeList;
               title=record.name + this.i18n('assignMenu.groupAuthTitle','授权组列表');
           }else {
               params = {pkId: record.groupId,dimId: record.dimId,};
               if (this.tenantId) {
                   params.tenantId = this.tenantId;
               }
               title=record.name + this.i18n('assignMenu.menuAuthTitle','菜单授权')
           }
            // 获取当前应用
            let appId = this.curApp.appId;
            if (appId) {
                params.appId = appId;
            }
            let conf = {
                curVm: this,
                data: params,
                widthHeight:widthHeight,
                component: component,
                title: title
            };
            Util.open(conf, function (action) {
            });
        },

        /**
         * 处理维度修改的事件。
         * @param dimension
         */
        handDimChange(dimension){
            this.expandedKeyList = [];
            this.currentDim = dimension;
            this.dimShowType = dimension.showType;
            this.isCompany = false;

            this.queryParam = {
                Q_DIM_ID__S_EQ:this.currentDimId
            }

            //初始化数据
            this.rankLevel = -1;
            this.currentGroupId = '';
            //查询用户组
            this.initGroups();

            OsRelTypeApi.getOsRelTypeOfGroupUser(this.currentDimId, '', this.tenantId).then(res => {
                this.loadUserTabs(res.data);
            })
            OsRelTypeApi.getOsRelTypeOfGroupGroup(this.currentDimId, '', this.tenantId).then(res => {
                this.loadGroupTabs(res.data);
            })
            this.initRankData(this.currentDimId);
        },

        /**
         * 读取用户组。
         * @returns {Promise<void>}
         */
        async initGroups() {
            let self_=this;
            if (!this.currentDimId) {
                this.groupData = [];
                return;
            }

            if (this.dimShowType != "TREE") {
                let {data,totalCount} = await this.getFlatGroups();
                this.groupData=data;
                this.totalCount=totalCount;
            } else {
                OsGroupApi.queryGroups(this.currentDimId, "0", "no", this.tenantId).then(result => {
                    let groups = result.data.map(item => {
                        let obj= item.childAmount && item.childAmount > 0 ? {...item, children: []} : {...item};
                        return obj;
                    });
                    self_.groupData=groups;
                    self_.expandedKeyList.push(groups[0].groupId);
                    this.handleExpandClick(true,groups[0])
                })
            }
        },
        searchGroup:debounce(async function (e) {
            let {value} = e.target;
            if (!value) {

                this.queryParam.Q_NAME__S_LK = '';
                this.searchFlag = false;
                //this.initGroups();
                return;
            }
            //搜索
            this.searchFlag = true;
            this.queryParam.Q_NAME__S_LK = value;
            let {data,totalCount} = await this.getFlatGroups();
            this.searchResult=data;
            this.totalCount=totalCount;
        },500),
        /**
         * 返回平铺的用户组。
         * @returns {Promise<void>}
         */
        async getFlatGroups(pageNo=1,pageSize=20){
            let self_=this;
            let params=this.queryParam;
            params.tenantId=self_.tenantId;
            let _parameter = {
                pageNo:pageNo,
                pageSize:pageSize,
                sortOrder: "desc",
                params:params
            };
            let res =await OsGroupApi.getOsUserGroupByDimId(_parameter);
            let result=res.result;
            return result;
        },

        loadUserTabs(data) {
            //组织分级管理
            if (this.supportGrade) {
                //维度为行政组织并且组织类型为公司
                if (this.currentDimId == "1" && this.orgType == 1) {
                    this.handleCompany();
                    return;
                }
            }
            this.userPanes.length = 0//清空
            const self = this
            data.map(function (type, index, arr) {
                const activeKey = type.key
                const activeName = type.name
                self.userPanes.push({title: `${activeName}`, key: activeKey, relTypeId: type.id})
                if (index == 0) {
                    self.userActiveKey = activeKey
                }
            })
        },
        loadGroupTabs(data) {
            this.groupPanes.length = 0//清空
            const self = this;
            self.groupActiveKey="";
            data.map(function (type, index, arr) {
                const activeKey = type.key
                const activeName = type.name
                self.groupPanes.push({
                    title: `${activeName}`,
                    key: activeKey,
                    relTypeId: type.id,
                    dimId2: type.dimId2,
                    relType: type.relType
                })
                if (index == 0) {
                    self.groupActiveKey = activeKey
                }
            })
        },

        selectGroup(record) {
            this.rankLevel = record.rankLevel;
            this.currentGroupId = record.groupId;
            this.currentGroup = record;
            //组织分级管理
            if (this.supportGrade) {
                this.orgType = record.type;
                //维度为行政组织并且组织类型为公司
                if (this.currentDimId == "1" && this.orgType == 1) {
                    this.isCompany = true;
                } else {
                    this.isCompany = false;
                }
            } else {
                this.isCompany = false;
            }

        },
        handGroupSelect(selectedRowKeys, selectedRows){
            this.selectGroup(selectedRows[0]);
        },
        /**
         * 根据维度初始化等级数据
         * @param dimId
         */
        initRankData(dimId) {
            var obj = {Q_DIM_ID__S_EQ: dimId};
            //增加租户
            if (this.tenantId) {
                obj.tenantId = this.tenantId;
            }
            const params = {params: obj}
            OsRankTypeApi.query(params).then(res => {
                this.rankData = res.data.map(rank => ({
                    title: rank.name,
                    value: rank.rkId,
                    level: rank.level
                }))
            })
        },
        handleCompany() {
            //行政组织类型为公司
            this.userPanes.length = 0; //清空
            const activeKey = 'GROUP-ADMIN';
            this.userPanes.push({title: this.i18n('list.admin','公司管理员'), key: activeKey, relTypeId: 1});
            this.userActiveKey = activeKey;
        },
        /**
         * 获取公司是否支持分公司管理。
         */
        getSupportGradeConfig() {
            OsGroupApi.getSupportGradeConfig().then(res => {
                this.supportGrade = res;
            })
        },
        /**
         * 当分页变更时重新获取数据。
         * @param page
         * @param pageSize
         * @returns {Promise<void>}
         */
        async onPageChange(page,pageSize){
            let {data,totalCount} = await this.getFlatGroups(page,pageSize);
            this.totalCount=totalCount;
            if (this.searchFlag){
                this.searchResult = data
            }else{
                this.groupData = data;
            }
        }

    },
    watch: {
        currentGroupId: function (val, oldVal) {
            OsRelTypeApi.getOsRelTypeOfGroupUser(this.currentDimId, this.rankLevel, this.tenantId).then(res => {
                this.loadUserTabs(res.data);
            })
            OsRelTypeApi.getOsRelTypeOfGroupGroup(this.currentDimId, this.rankLevel, this.tenantId).then(res => {
                this.loadGroupTabs(res.data);
            })
        },
        '$route': {
            handler: function (val) {

                this.tenantId = val.params.tenantId;
                this.init();
            },
            deep: true
        }
    }
}